package com.hxminer.hxwebs.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hxminer.hxwebs.dao.OrderDao;
import com.hxminer.hxwebs.dao.OrderDetailDao;
import com.hxminer.hxwebs.enmus.ResultEnum;
import com.hxminer.hxwebs.exceptions.HxException;
import com.hxminer.hxwebs.model.*;
import com.hxminer.hxwebs.repository.AddressRespository;
import com.hxminer.hxwebs.repository.OrdersDetailRepository;
import com.hxminer.hxwebs.repository.OrdersRepository;
import com.hxminer.hxwebs.utils.OrdersIdUtil;
import com.hxminer.hxwebs.utils.ResultUitl;
import com.hxminer.hxwebs.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * Author YRG
 * Created by on 2018/5/16.
 * Describe
 */
@Service
public class OrdersService {


    @Autowired
    OrdersRepository ordersRepository;

    @Autowired
    OrderDao orderDao;

    @Autowired
    AddressRespository addressRespository;

    @Autowired
    OrdersDetailRepository ordersDetailRepository;

    @Autowired
    OrderDetailDao orderDetailDao;

    /**
     * 提交订单
     *
     * @param orders
     * @return
     */
    public Result<ReOrderNo> commitOrders(ReOrders orders) throws Exception {
        if (orders == null || "".equals(orders.getUsername()) || null == orders.getUsername()) {
            throw new HxException(ResultEnum.ORDER_COMMIT_ERROR);
        }
        String orderId = OrdersIdUtil.getOrderIdByTime(); //生成订单号

        System.out.println("orders:" + orders.toString());

        Orders order = new Orders();
        order.setUserId(orders.getUserId());//用户ID
        order.setUsername(orders.getUsername());//用户名
        order.setOrdersNo(orderId);//订单号
        order.setOrdersAllPrice(orders.getOrdersAllPrice());//用户生成订单时总价钱
        order.setOrdersData(orders.getOrdersData());//时间
        order.setOrdersInfo(orders.getOrdersInfo());//说明
        ordersRepository.save(order);//插入数据库

        String orderDetails = orders.getOrderDetails();//获取订单详情
        JSONArray jsonArray = JSONArray.parseArray(orderDetails);
        System.out.println("jsonArray:" + jsonArray.toJSONString());
        for (int i = 0, len = jsonArray.size(); i < len; i++) {
            OrderDetails orderDetails1 = new OrderDetails();
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            orderDetails1.setUserId(jsonObject.getString("userId"));
            orderDetails1.setUsername(jsonObject.getString("username"));
            orderDetails1.setProductTime(jsonObject.getString("productTime"));
            orderDetails1.setProductName(jsonObject.getString("productName"));
            orderDetails1.setProductType(jsonObject.getString("productType"));
            orderDetails1.setPrice(jsonObject.getDouble("price"));
            orderDetails1.setProductNo(jsonObject.getString("productNo"));
            orderDetails1.setProductAmount(jsonObject.getInteger("productAmount"));
            orderDetails1.setTypeTotalPrice(jsonObject.getDouble("typeTotalPrice"));
            orderDetails1.setOrderNo(orderId);
            ordersDetailRepository.save(orderDetails1);//插入选择订单
        }

        ReOrderNo reOrderNo = new ReOrderNo();
        reOrderNo.setOrderNo(orderId);
        reOrderNo.setUrl("confirm-order.html");
        return ResultUitl.success(ResultEnum.ORDER_COMMIT_SUCCESS, reOrderNo);
    }


    /**
     * 查找当前用户订单
     *
     * @param orders
     * @return
     */
    public Result<ReOrders> findByUserOrders(ReOrders orders) throws Exception {

        return getReOrdersResult(orders);
    }

    private Result<ReOrders> getReOrdersResult(ReOrders orders) throws Exception {

        if (orders == null) {
            throw new HxException(ResultEnum.ORDER_GET_ERROR);
        }
        String ordersNo = orders.getOrdersNo();
        String userId = orders.getUserId();
        String username = orders.getUsername();
        List<Orders> ordersList = orderDao.findByUserIdAndUsernameAndOrdersNo(userId, username, ordersNo);
        List<OrderDetails> orderDetails = orderDetailDao.findByUserIdAndUsernameAndOrderNo(userId, username, ordersNo);


        if (ordersList == null || ordersList.size() <= 0 || orderDetails == null || orderDetails.size() <= 0) {
            throw new HxException(ResultEnum.ORDER_GET_ERROR);//获取订单失败
        } else {

            Orders orders1 = ordersList.get(0);
            ReOrders reOrders = new ReOrders();
            reOrders.setUserId(orders1.getUserId());
            reOrders.setUsername(orders1.getUsername());
            reOrders.setOrdersAllPrice(orders1.getOrdersAllPrice());
            reOrders.setOrdersData(orders1.getOrdersData());
            reOrders.setOrdersNo(orders1.getOrdersNo());
            reOrders.setOrdersInfo(orders1.getOrdersInfo());
            reOrders.setReceiveAddress(orders1.getReceiveAddress());
            reOrders.setReceiveName(orders1.getReceiveName());
            reOrders.setReceivePhone(orders1.getReceivePhone());
            reOrders.setOrdersNote(orders1.getOrdersNote());
            reOrders.setIsCompletePay(orders1.getIsCompletePay());
            reOrders.setOrderDetailsList(orderDetails);
            return ResultUitl.success(ResultEnum.ORDER_GENERATE_SUCCESS, reOrders);
        }
    }


    /**
     * 保存订单完整
     *
     * @param orders
     * @return
     * @throws Exception
     */
    public Result<ReOrderNo> completeOrders(ReOrders orders) throws Exception {

        if (null == orders) {
            throw new HxException(ResultEnum.ORDER_GET_ERROR);
        }
        String ordersNo = orders.getOrdersNo();
        String userId = orders.getUserId();
        String username = orders.getUsername();
        List<Orders> ordersList = orderDao.findByUserIdAndUsernameAndOrdersNo(userId, username, ordersNo);
        List<OrderDetails> orderDetails = orderDetailDao.findByUserIdAndUsernameAndOrderNo(userId, username, ordersNo);
        String orderData = TimeUtil.currentToTime();
        if (ordersList == null || ordersList.size() <= 0 || orderDetails == null || orderDetails.size() <= 0) {
            throw new HxException(ResultEnum.ORDER_GET_ERROR);//获取订单失败
        } else {
            Orders orders1 = ordersList.get(0);
            orders1.setOrdersData(orderData);//提交订单时间
            orders1.setReceiveName(orders.getReceiveName());//接收用户
            orders1.setOrdersNote(orders.getOrdersNote());//备注
            orders1.setReceiveAddress(orders.getReceiveAddress());//地址
            orders1.setIsCompletePay(1);//是否完成交易
            orders1.setReceivePhone(orders.getReceivePhone());//接收电话
            orderDao.save(orders1);//更新数据
            for (int i = 0, len = orderDetails.size(); i < len; i++) {
                OrderDetails orderDetails1 = orderDetails.get(i);
                orderDetails1.setProductTime(orderData);
                orderDetails1.setReceiveName(orders.getReceiveName());
                orderDetails1.setReceiveAddress(orders.getReceiveAddress());
                orderDetails1.setReceivePhone(orders.getReceivePhone());
                orderDetails1.setOrdersNote(orders.getOrdersNote());
                orderDetails1.setIsCompletePay(1);//1表示未支付，0表示已支付
                orderDetails1.setIsOrderReview(1);//1表示未审核，0表示已审核
                orderDetailDao.save(orderDetails1);//更新订单详情
            }
            ReOrderNo reOrderNo = new ReOrderNo();
            reOrderNo.setUrl("pay.html");
            reOrderNo.setOrderNo(orders1.getOrdersNo());
            return ResultUitl.success(ResultEnum.ORDER_COMMIT_SUCCESS, reOrderNo);//返回数据
        }
    }


    /**
     * @param orders
     * @return
     * @throws Exception
     */
    public Result<ReOrders> givePayOrder(ReOrders orders) throws Exception {
        return getReOrdersResult(orders);
    }

    /**
     * 获取历史订单
     *
     * @param
     * @return
     */
    public Result<Page<OrderDetails>> giveByHistoryOrderDetails(@Valid ReOrderNo reOrder) throws Exception {

        if ("".equals(reOrder.getObj()) || null == reOrder) {
            throw new HxException(ResultEnum.OBJECT_COMMIT_ERROR);
        }

        JSONObject jsonObject = JSONObject.parseObject(reOrder.getObj());
        String username = jsonObject.getString("username");
        String userId = jsonObject.getString("userId");
        Integer page = jsonObject.getInteger("page");
        Integer sel_status = jsonObject.getInteger("sel_status");
        String search_content = jsonObject.getString("search_content");
//        Pageable pageable = new PageRequest(page - 1, 5);
////        List<OrderDetails> orderDetailsList = ordersDetailRepository.findAll(pageable);
//        List<OrderDetails> orderDetailsList = ordersDetailRepository.findAllByUsernameAndUserId(username, userId, pageable);

        Page<OrderDetails> orderDetailsPage = null;
        Sort sort = new Sort(Sort.Direction.DESC, "productTime");
        Pageable pageable = new PageRequest(page - 1, 10, sort);
        if ("".equals(search_content) && 2 == sel_status) {
            orderDetailsPage = ordersDetailRepository.findAllByUsernameAndUserId(username, userId, pageable);
        } else if (!"".equals(search_content) && 2 == sel_status) {
            orderDetailsPage = ordersDetailRepository.findAllByUsernameAndUserIdAndOrderNo(username, userId, search_content, pageable);
        } else if (!"".equals(search_content) && 1 == sel_status) {
            orderDetailsPage = ordersDetailRepository.findAllByUsernameAndUserIdAndOrderNoAndIsCompletePay(username, userId, search_content, sel_status, pageable);
        } else if (!"".equals(search_content) && 0 == sel_status) {
            orderDetailsPage = ordersDetailRepository.findAllByUsernameAndUserIdAndOrderNoAndIsCompletePay(username, userId, search_content, sel_status, pageable);
        } else if ("".equals(search_content) && 1 == sel_status || 0 == sel_status) {
            orderDetailsPage = ordersDetailRepository.findByUsernameAndUserIdAndIsCompletePay(username, userId, sel_status, pageable);
        }
        if (null == orderDetailsPage || orderDetailsPage.getSize() == 0) {
            return ResultUitl.success(ResultEnum.HISTORY_ORDER_ERROR, orderDetailsPage);
        } else {
            return ResultUitl.success(ResultEnum.SUCCESS, orderDetailsPage);
        }
    }
}
